﻿using LD.Host;
using System;
using System.Diagnostics;
using System.Text;
using System.Threading;

namespace LD
{
    public class ScanerHelper : BaseCommunication
    {
        private ManualResetEvent m_waitReceiveData = new ManualResetEvent(false);
        public ScanerHelper(TcpIpParameModel param)
        {
            Parame = param;
            m_Socket = new SocketHelper(Parame.Ip, Parame.Port);
            m_Socket.ConnectionEvent += M_Socket_ConnectionEvent;
            m_Socket.ReceiveDataEvent += M_Socket_ReceiveDataEvent;
        }

        private void M_Socket_ConnectionEvent(bool obj)
        {
            ConnectionStateEvent?.Invoke(Parame.Name, obj ? Status.成功 : Status.失败);
        }
        public TcpIpParameModel Parame { get; private set; }
        public override void Connect()
        {
            m_Socket.CreateConnect();
        }
        private void M_Socket_ReceiveDataEvent(byte[] obj)
        {
            m_Barcode = Encoding.UTF8.GetString(obj);
            m_waitReceiveData.Set();
        }
        private string m_Barcode;
        /// <summary>
        /// 读码
        /// </summary>
        /// <returns></returns>
        public override object Send(string content)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            m_Barcode = string.Empty;
            Log4.Info($"【{Parame.Name}】请求读码");
            try
            {
                while (stopwatch.ElapsedMilliseconds < 3000 && string.IsNullOrEmpty(m_Barcode))
                {
                    m_waitReceiveData.Reset();

                    m_Socket.Send("start");

                    m_waitReceiveData.WaitOne(610);
                    Log4.Info($"【{Parame.Name}】条码信息【{m_Barcode}】");

                    if (m_Barcode.Contains("NoRead")
                        || m_Barcode.Contains("NR"))
                        m_Barcode = string.Empty;
                }
            }
            catch (Exception ex)
            {
                Log4.Error($"【{Parame.Name}】{ex.Message}");
            }
            finally
            {
                stopwatch.Stop();
            }
            //LogHelper.Log(LogType.PC_Sock, $"【{alias}】读码结束", LogLevel.一般);
            return m_Barcode;
        }
        private SocketHelper m_Socket;
        public override void Closed()
        {
            m_Socket?.Closed();
        }
    }
}
